package com.pingao.mp.modular.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pingao.mp.modular.sys.entity.Menu;
import com.pingao.mp.modular.sys.entity.Permission;
import com.pingao.mp.modular.sys.entity.Role;
import com.pingao.mp.modular.sys.entity.User;
import com.pingao.mp.modular.sys.service.PermissionService;
import com.pingao.mp.modular.sys.service.RoleService;
import com.pingao.mp.utils.Constant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 闻品高
 * @since 2018-09-26
 */
@Controller
@RequestMapping("/sys/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @GetMapping("/index")
    @RequiresPermissions("sys.role.index")
    public String index() {
        return "sys/role/index";
    }

    @GetMapping("/list")
    @ResponseBody
    @RequiresPermissions("sys.role.index")
    public Object list(@RequestParam("pageNumber") Integer pageNumber,
                       @RequestParam("pageSize") Integer pageSize,
                       @RequestParam("searchText") String searchText,
                       @RequestParam("sortName") String sortName,
                       @RequestParam("sortOrder") String sortOrder) {
        return roleService.getRoleList(pageNumber, pageSize, searchText, sortName, sortOrder);
    }

    @GetMapping("/add")
    @RequiresPermissions("sys.role.add")
    public String add() {
        return "sys/role/add";
    }

    @PostMapping("/add")
    @RequiresPermissions("sys.role.add")
    @ResponseBody
    public Object add(Role role) {
        Map<String, Object> map = new HashMap<>();
        //判断角色code是否已经存在
         if(roleService.getOne(new QueryWrapper<Role>().eq(Role.COL_CODE, role.getCode()).isNull(Role.COL_DELETE_TIME)) != null){
             map.put("status",false);
             map.put("msg","角色code已经存在，请填写不存在的code");
             return map;
         }
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User u = (User) session.getAttribute(Constant.LoginUser);
        if (u == null) {
            map.put("status", false);
            map.put("msg", "用户没登录");
            return map;
        }
        role.setUserId(u.getId());
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        if (!roleService.save(role)) {
            map.put("status", false);
            map.put("msg", "保存角色出错......");
            return map;
        }
        map.put("status", true);
        map.put("msg", "保存角色成功");
        map.put("role", role);
        return map;
    }

    @PostMapping("/delete")
    @RequiresPermissions("sys.role.delete")
    @ResponseBody
    public Object delete(
            @RequestParam(value = "ids[]") List<Long> ids
    ) {
        Map<String, Object> map = new HashMap<>();
        for (Long id : ids) {
            if (id.equals(1L)) {
                continue;//不能删除admin角色
            }
            //删除权限表中关于该角色的信息
            permissionService.remove(new QueryWrapper<Permission>().eq(Permission.COL_ROLE_ID,id));
            roleService.deleteRoleById(id);
        }
        map.put("status", true);
        map.put("msg", "删除成功");
        map.put("ids", ids);
        return map;
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("sys.role.edit")
    public String edit(@PathVariable("id") Long id, ModelMap map) {
        Role role = roleService.getById(id);
        if (role == null) {
            throw new NullPointerException("该角色不存在--this role is not exits!!!");
        }
        map.addAttribute("role", role);
        return "sys/role/edit";
    }

    @PostMapping("/edit")
    @ResponseBody
    @RequiresPermissions("sys.role.edit")
    public Object edit(Role role) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //判断code是否在其他 role里存在
        if(roleService.getOne(new QueryWrapper<Role>().eq(Role.COL_CODE, role.getCode()).isNull(Role.COL_DELETE_TIME).notIn(Role.COL_ID,role.getId())) != null) {
            map.put("status", false);
            map.put("msg", "角色code已经存在，请填写不存在的code");
            return map;
        }
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User u = (User) session.getAttribute(Constant.LoginUser);
        if (u == null) {
            throw new Exception("用户没登录");
        }
        role.setUserId(u.getId());
        role.setUpdateTime(LocalDateTime.now());
        roleService.updateById(role);
        map.put("status", true);
        map.put("msg", "保存角色成功");
        map.put("role", role);
        return map;
    }

    @GetMapping("/roleSetting/{id}")
    @RequiresPermissions("sys.role.roleSetting")
    public String role(@PathVariable("id") Long id, ModelMap map) {
        Role role = roleService.getById(id);
        if (role == null) {
            throw new NullPointerException("该角色不存在--this role is not exits!!!");
        }
        map.addAttribute("role", role);
        return "sys/role/role";
    }

    @GetMapping("/menu/{id}")
    @ResponseBody
    @RequiresPermissions("sys.role.roleSetting")
    public Object menu(@PathVariable("id") Long id) {
        Map<String, Object> map = new HashMap<>();
        List<Menu> menus = roleService.getMenuList(id);
        map.put("rows", menus);
        return map;
    }

    @PostMapping("/roleSetting/{id}")
    @ResponseBody
    @RequiresPermissions("sys.role.roleSetting")
    public Object role(@PathVariable("id") Long id,@RequestParam("menuIds[]") List<Long> menuIds) {
        Role role = roleService.getById(id);
        if (role == null) {
            throw new NullPointerException("该角色不存在--this role is not exits!!!");
        }
        Map<String,Object> map = new HashMap<>();
        roleService.savePermissions(id,menuIds);
        map.put("status", true);
        map.put("msg", "权限设置成功");
        map.put("role",role);
        map.put("menuIds",menuIds);
        return map;
    }
}